<script setup>
import { onMounted, ref, onUnmounted, watch } from 'vue'
import * as echarts from 'echarts'
import { useResourceMonitor } from '../../../composables/useResourceMonitor'

// 使用资源监控组合式函数
const { gpuUsageData, networkDelayData, startPolling, stopPolling } = useResourceMonitor()

let edge1Chart = null
let edge2Chart = null
let cloudChart = null

const initCharts = () => {
  edge1Chart = echarts.init(document.getElementById('edge1Chart'))
  edge2Chart = echarts.init(document.getElementById('edge2Chart'))
  cloudChart = echarts.init(document.getElementById('cloudChart'))

  const edge1Option = {
    title: {
      text: '边侧1',
      textStyle: {
        color: '#7ecbcf',
        fontSize: 10,
        fontWeight: 'normal'
      },
      left: 'center'
    },
    tooltip: {
      trigger: 'axis',
      axisPointer: {
        type: 'cross',
        crossStyle: {
          color: '#999'
        }
      },
      confine: true,
      backgroundColor: 'rgba(16, 44, 58, 0.9)',
      borderColor: '#3eacb4',
      borderWidth: 1,
      textStyle: {
        color: '#fff'
      },
      extraCssText: 'border-radius: 4px; box-shadow: 0 0 10px rgba(62, 172, 180, 0.3);',
      formatter: function (params) {
        let html = `<div style="font-size:12px;color:#fff;line-height:1.2;padding:5px">时间点: ${params[0].name}</div>`
        params.forEach((param) => {
          let color = param.color
          let name = param.seriesName
          let value = param.value
          let unit = name === 'GPU使用率' ? '%' : 'ms'
          html += `<div style="display:flex;align-items:center;margin-top:3px">
                    <span style="display:inline-block;width:8px;height:8px;background:${color};border-radius:50%;margin-right:6px"></span>
                    <span style="font-size:11px;color:#a8c1c3">${name}: </span>
                    <span style="float:right;margin-left:10px;font-size:11px;color:#fff;font-weight:bold">${value}${unit}</span>
                   </div>`
        })
        return html
      }
    },
    // legend: {
    //   data: ['GPU使用率', '网络延迟'],
    //   textStyle: {
    //     color: '#a8c1c3',
    //     fontSize: 10
    //   },
    //   right: '5%',
    //   top: '8%'
    // },
    grid: {
      top: '18%',
      left: '14%',
      right: '14%',
      bottom: '18%'
    },
    xAxis: [
      {
        type: 'category',
        data: ['1', '2', '3', '4', '5'],
        axisPointer: {
          type: 'shadow'
        },
        axisLabel: {
          color: '#a8c1c3',
          fontSize: 10
        },
        axisLine: {
          show: false
        },
        axisTick: {
          show: false
        }
      }
    ],
    yAxis: [
      {
        type: 'value',
        name: 'GPU使用率',
        nameTextStyle: {
          color: '#a8c1c3',
          fontSize: 10
        },
        min: 0,
        max: 100,
        interval: 20,
        axisLabel: {
          formatter: '{value}',
          color: '#a8c1c3',
          fontSize: 10
        },
        splitLine: {
          lineStyle: {
            color: 'rgba(62, 172, 180, 0.1)'
          }
        },
        axisLine: {
          show: false
        },
        axisTick: {
          show: false
        }
      },
      {
        type: 'value',
        name: '网络延迟',
        nameTextStyle: {
          color: '#a8c1c3',
          fontSize: 10
        },
        min: 0,
        max: 1000,  // TODO: 根据真实网络的延迟情况决定
        interval: 200,
        axisLabel: {
          formatter: '{value}',
          color: '#a8c1c3',
          fontSize: 10
        },
        splitLine: {
          show: false
        },
        axisLine: {
          show: false
        },
        axisTick: {
          show: false
        }
      }
    ],
    series: [
      {
        name: 'GPU使用率',
        type: 'line',
        yAxisIndex: 0,
        smooth: true,
        symbol: 'circle',
        symbolSize: 6,
        data: gpuUsageData.value.edge1,
        lineStyle: {
          width: 3,
          color: new echarts.graphic.LinearGradient(0, 0, 1, 0, [
            { offset: 0, color: '#3eacb4' },
            { offset: 1, color: '#09c4ca' }
          ])
        },
        itemStyle: {
          color: '#3eacb4',
          borderWidth: 2,
          borderColor: '#fff'
        }
      },
      {
        name: '网络延迟',
        type: 'bar',
        yAxisIndex: 1,
        data: networkDelayData.value.edge1,
        barWidth: '40%',
        itemStyle: {
          color: new echarts.graphic.LinearGradient(0, 0, 0, 1, [
            { offset: 0, color: '#f29701' },
            { offset: 1, color: '#e07b00' }
          ]),
          borderRadius: [3, 3, 0, 0]
        }
      }
    ]
  }

  const edge2Option = {
    title: {
      text: '边侧2',
      textStyle: {
        color: '#7ecbcf',
        fontSize: 10,
        fontWeight: 'normal'
      },
      left: 'center'
    },
    tooltip: {
      trigger: 'axis',
      axisPointer: {
        type: 'cross',
        crossStyle: {
          color: '#999'
        }
      },
      confine: true,
      backgroundColor: 'rgba(16, 44, 58, 0.9)',
      borderColor: '#3eacb4',
      borderWidth: 1,
      textStyle: {
        color: '#fff'
      },
      extraCssText: 'border-radius: 4px; box-shadow: 0 0 10px rgba(62, 172, 180, 0.3);',
      formatter: function (params) {
        let html = `<div style="font-size:12px;color:#fff;line-height:1.2;padding:5px">时间点: ${params[0].name}</div>`
        params.forEach((param) => {
          let color = param.color
          let name = param.seriesName
          let value = param.value
          let unit = name === 'GPU使用率' ? '%' : 'kb/s'
          html += `<div style="display:flex;align-items:center;margin-top:3px">
                    <span style="display:inline-block;width:8px;height:8px;background:${color};border-radius:50%;margin-right:6px"></span>
                    <span style="font-size:11px;color:#a8c1c3">${name}: </span>
                    <span style="float:right;margin-left:10px;font-size:11px;color:#fff;font-weight:bold">${value}${unit}</span>
                   </div>`
        })
        return html
      }
    },
    // legend: {
    //   data: ['GPU使用率', '网络延迟'],
    //   textStyle: {
    //     color: '#a8c1c3',
    //     fontSize: 10
    //   },
    //   right: '5%',
    //   top: '8%'
    // },
    grid: {
      top: '18%',
      left: '14%',
      right: '14%',
      bottom: '18%'
    },
    xAxis: [
      {
        type: 'category',
        data: ['1', '2', '3', '4', '5'],
        axisPointer: {
          type: 'shadow'
        },
        axisLabel: {
          color: '#a8c1c3',
          fontSize: 10
        },
        axisLine: {
          show: false
        },
        axisTick: {
          show: false
        }
      }
    ],
    yAxis: [
      {
        type: 'value',
        name: 'GPU使用率',
        nameTextStyle: {
          color: '#a8c1c3',
          fontSize: 10
        },
        min: 0,
        max: 100,
        interval: 20,
        axisLabel: {
          formatter: '{value}',
          color: '#a8c1c3',
          fontSize: 10
        },
        splitLine: {
          lineStyle: {
            color: 'rgba(62, 172, 180, 0.1)'
          }
        },
        axisLine: {
          show: false
        },
        axisTick: {
          show: false
        }
      },
      {
        type: 'value',
        name: '网络延迟',
        nameTextStyle: {
          color: '#a8c1c3',
          fontSize: 10
        },
        min: 0,
        max: 1000,
        interval: 200,
        axisLabel: {
          formatter: '{value}',
          color: '#a8c1c3',
          fontSize: 10
        },
        splitLine: {
          show: false
        },
        axisLine: {
          show: false
        },
        axisTick: {
          show: false
        }
      }
    ],
    series: [
      {
        name: 'GPU使用率',
        type: 'line',
        yAxisIndex: 0,
        smooth: true,
        symbol: 'circle',
        symbolSize: 6,
        data: gpuUsageData.value.edge2,
        lineStyle: {
          width: 3,
          color: new echarts.graphic.LinearGradient(0, 0, 1, 0, [
            { offset: 0, color: '#3eacb4' },
            { offset: 1, color: '#09c4ca' }
          ])
        },
        itemStyle: {
          color: '#3eacb4',
          borderWidth: 2,
          borderColor: '#fff'
        }
      },
      {
        name: '网络延迟',
        type: 'bar',
        yAxisIndex: 1,
        data: networkDelayData.value.edge2,
        barWidth: '40%',
        itemStyle: {
          color: new echarts.graphic.LinearGradient(0, 0, 0, 1, [
            { offset: 0, color: '#f29701' },
            { offset: 1, color: '#e07b00' }
          ]),
          borderRadius: [3, 3, 0, 0]
        }
      }
    ]
  }

  const cloudOption = {
    title: {
      text: '云侧',
      textStyle: {
        color: '#7ecbcf',
        fontSize: 10,
        fontWeight: 'normal'
      },
      left: 'center'
    },
    tooltip: {
      trigger: 'axis',
      axisPointer: {
        type: 'line',
        lineStyle: {
          color: '#3eacb4',
          width: 1,
          type: 'dashed'
        }
      },
      confine: true,
      backgroundColor: 'rgba(16, 44, 58, 0.9)',
      borderColor: '#3eacb4',
      borderWidth: 1,
      textStyle: {
        color: '#fff'
      },
      extraCssText: 'border-radius: 4px; box-shadow: 0 0 10px rgba(62, 172, 180, 0.3);',
      formatter: function (params) {
        let param = params[0]
        let html = `<div style="font-size:12px;color:#fff;line-height:1.2;padding:5px">时间点: ${param.name}</div>
                    <div style="display:flex;align-items:center;margin-top:3px">
                      <span style="display:inline-block;width:8px;height:8px;background:${param.color};border-radius:50%;margin-right:6px"></span>
                      <span style="font-size:11px;color:#a8c1c3">${param.seriesName}: </span>
                      <span style="float:right;margin-left:10px;font-size:11px;color:#fff;font-weight:bold">${param.value}%</span>
                    </div>`
        return html
      }
    },
    // legend: {
    //   data: ['GPU使用率'],
    //   textStyle: {
    //     color: '#a8c1c3',
    //     fontSize: 10
    //   },
    //   right: '5%',
    //   top: '8%'
    // },
    grid: {
      top: '18%',
      left: '14%',
      right: '14%',
      bottom: '18%'
    },
    xAxis: {
      type: 'category',
      boundaryGap: false,
      data: ['1', '2', '3', '4', '5'],
      axisLabel: {
        color: '#a8c1c3',
        fontSize: 10
      },
      axisLine: {
        show: false
      },
      axisTick: {
        show: false
      }
    },
    yAxis: {
      type: 'value',
      name: 'GPU使用率',
      nameTextStyle: {
        color: '#a8c1c3',
        fontSize: 10
      },
      min: 0,
      max: 100,
      interval: 20,
      axisLabel: {
        color: '#a8c1c3',
        fontSize: 10,
        formatter: '{value}'
      },
      splitLine: {
        lineStyle: {
          color: 'rgba(62, 172, 180, 0.1)'
        }
      },
      axisLine: {
        show: false
      },
      axisTick: {
        show: false
      }
    },
    series: [
      {
        name: 'GPU使用率',
        type: 'line',
        smooth: true,
        symbol: 'circle',
        symbolSize: 6,
        data: gpuUsageData.value.cloud,
        lineStyle: {
          width: 3,
          color: new echarts.graphic.LinearGradient(0, 0, 1, 0, [
            { offset: 0, color: '#3eacb4' },
            { offset: 1, color: '#09c4ca' }
          ])
        },
        itemStyle: {
          color: '#3eacb4',
          borderWidth: 2,
          borderColor: '#fff'
        },
        areaStyle: {
          color: new echarts.graphic.LinearGradient(0, 0, 0, 1, [
            { offset: 0, color: 'rgba(62, 172, 180, 0.3)' },
            { offset: 1, color: 'rgba(62, 172, 180, 0.05)' }
          ])
        }
      }
    ]
  }

  edge1Chart.setOption(edge1Option)
  edge2Chart.setOption(edge2Option)
  cloudChart.setOption(cloudOption)
}

// 更新图表
const updateCharts = () => {
  if (edge1Chart && edge2Chart && cloudChart) {
    try {
      console.log('更新图表数据:', {
        edge1: gpuUsageData.value.edge1,
        edge2: gpuUsageData.value.edge2,
        cloud: gpuUsageData.value.cloud,
        networkEdge1: networkDelayData.value.edge1,
        networkEdge2: networkDelayData.value.edge2
      })
      
      // 通过完整设置选项来更新，避免部分更新可能导致的问题
      edge1Chart.setOption({
        series: [
          { 
            name: 'GPU使用率',
            data: gpuUsageData.value.edge1 
          },
          { 
            name: '网络延迟',
            data: networkDelayData.value.edge1 
          }
        ]
      }, false, true) // 第三个参数设为 true，强制不合并，全量覆盖
      
      edge2Chart.setOption({
        series: [
          { 
            name: 'GPU使用率',
            data: gpuUsageData.value.edge2 
          },
          { 
            name: '网络延迟',
            data: networkDelayData.value.edge2 
          }
        ]
      }, false, true)
      
      cloudChart.setOption({
        series: [
          { 
            name: 'GPU使用率',
            data: gpuUsageData.value.cloud 
          }
        ]
      }, false, true)
    } catch (error) {
      console.error('更新图表时出错:', error)
    }
  } else {
    console.warn('图表实例未初始化，无法更新')
  }
}

// 监听数据变化，更新图表
watch([() => gpuUsageData.value, () => networkDelayData.value], () => {
  console.log('数据变化触发图表更新')
  updateCharts()
}, { deep: true, immediate: false })

onMounted(() => {
  initCharts()
  
  // 开始定时请求数据，每秒一次
  startPolling(1000)

  // 添加窗口大小变化时的自适应
  window.addEventListener('resize', handleResize)
})

const handleResize = () => {
  if (edge1Chart) edge1Chart.resize()
  if (edge2Chart) edge2Chart.resize()
  if (cloudChart) cloudChart.resize()
}

onUnmounted(() => {
  // 移除窗口大小变化的监听
  window.removeEventListener('resize', handleResize)
  
  // 清除定时器 (已在 useResourceMonitor 组合式函数中的 onUnmounted 钩子中处理)
  stopPolling()

  if (edge1Chart) edge1Chart.dispose()
  if (edge2Chart) edge2Chart.dispose()
  if (cloudChart) cloudChart.dispose()
})
</script>

<template>
  <div class="resource-monitor">
    <h3>云边资源监控</h3>
    <div class="charts-container">
      <div id="edge1Chart" class="chart"></div>
      <div id="edge2Chart" class="chart"></div>
      <div id="cloudChart" class="chart"></div>
    </div>
  </div>
</template>

<style lang="scss" scoped>
.resource-monitor {
  height: 100%;
  color: rgba(255, 255, 255, 0.8);

  h3 {
    margin-bottom: 10px;
    font-size: 0.9rem;
    font-weight: 500;
    text-align: center;
    color: #7ecbcf;
    letter-spacing: var(--letter-spacing-base);
  }

  .charts-container {
    display: flex;
    flex-direction: column;
    height: calc(100% - 30px);
  }

  .chart {
    width: 100%;
    height: 33%;
    margin-bottom: 5px;
    opacity: 0.8;
  }
}
</style>
